package com.example.sinaweibo2.logic;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.example.sinaweibo2.bean.Task;
import com.example.sinaweibo2.ui.IWeiboActivity;

public class MainService extends Service implements Runnable {
	private static Queue<Task> tasks = new LinkedList<Task>();
	private static ArrayList<Activity> activities = new ArrayList<Activity>();
	private Boolean isRun;
	private Handler handler;
	
	@Override
	public void onCreate() {
		super.onCreate();
		isRun = true;
		
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				
				if (!activities.isEmpty()) {
					
					switch (msg.what) {
					case Task.WEIBO_LOGIN:
						IWeiboActivity activity = (IWeiboActivity) getActivityByName("LoginActivity");

						if (activity != null) {
							activity.refresh(msg.obj);
						}
						break;

					default:
						break;
					}
				}
				
			}
		};
		new Thread(this).start();
	}
	
	@Override
	public void run() {
		
		while(isRun) {
			
			if (!tasks.isEmpty()) {
				
				Task task = tasks.poll();
				
				if (task != null) {
					doTask(task);
				}
			}
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	private void doTask(Task task) {
		Message msg = handler.obtainMessage();
		msg.what = task.getTaskId();
		
		switch (task.getTaskId()) {
		case Task.WEIBO_LOGIN:
			Log.i("laf", "dotask>>>>>weibo_login");
			msg.obj = "login success";
			
			break;
		default:
			break;
		}
		
		handler.sendMessage(msg);
	}

	private Activity getActivityByName(String activityName) {
		for (Activity activity : activities) {
			
			if (activity.getClass().getName().indexOf(activityName) != -1) {
	
				return activity;
			}
		}
		return null;
	}
	
	public static void newTask(Task task) {
		tasks.add(task);
	} 
	
	public static void addActivity(Activity activity) {
		activities.add(activity);
	}
}
